from py2neo import Graph

def merge_duplicates(graph, labels):
    """
    labels: 需要去重的标签列表，例如 ["甜味剂类型", "论文名称"]
    """
    for label in labels:
        print(f"\n=== 处理标签 `{label}` ===")

        # Step 1：写入标准化字段
        q1 = f"""
        MATCH (n:`{label}`)
        WHERE n.name IS NOT NULL
        SET n._norm = trim(toLower(coalesce(n.name,"")))
        RETURN count(n) AS touched
        """
        r1 = graph.run(q1).data()
        print(f"  ➜ 已规范化 name：{r1[0]['touched'] if r1 else 0} 个节点")

        # Step 2：按 _norm 分组并合并
        q2 = f"""
        MATCH (m:`{label}`)
        WITH m._norm AS node_name, m
        ORDER BY id(m)
        WITH node_name, collect(m) AS nodes
        WHERE node_name <> "" AND size(nodes) > 1
        CALL apoc.refactor.mergeNodes(
            nodes,
            {{properties:'combine', mergeRels:true}}
        ) YIELD node AS merged
        REMOVE merged._norm
        RETURN node_name AS name, size(nodes) AS merged_count
        """
        try:
            results = graph.run(q2).data()
            if results:
                total = sum(r["merged_count"] for r in results)
                print(f"  ✅ 合并完成：{len(results)} 组重复，共合并 {total} 个节点")
            else:
                print("  ✅ 未发现可合并的重复节点")
        except Exception as e:
            print(f"  ❌ 合并失败：{e}")

def main():
    # 根据实际情况修改连接信息
    NEO4J_URI = "neo4j://localhost:7687"
    NEO4J_USER = "neo4j"
    NEO4J_PASSWORD = "053116wj"

    try:
        graph = Graph(NEO4J_URI, auth=(NEO4J_USER, NEO4J_PASSWORD))
        graph.run("RETURN 1 AS ok LIMIT 1")
        print("✅ 成功连接 Neo4j 数据库")

        # 需要去重的标签列表
        target_labels = ["致甜成分的添加部位"]
        merge_duplicates(graph, target_labels)

        print("\n✨ 全部处理完成")
    except Exception as e:
        print(f"❌ 数据库连接或执行失败：{e}")

if __name__ == "__main__":
    main()
